package graphNeo4j

import org.neo4j.graphdb.GraphDatabaseService
import org.neo4j.graphdb.factory.GraphDatabaseFactory
import org.neo4j.graphdb.Transaction

object Graph {
  
	var graph: GraphDatabaseService = null
  
	def withTransactionInDatabase[T](f: () => T, neo4jDirectory: String): T = {
		if(graph == null) {
            graph = createDatabase(neo4jDirectory)
        }
		
		var result: T = null.asInstanceOf[T]
        var tx: Transaction = null
	  
	    try {
	    	val tx = graph.beginTx
	    	result = f()
	    	tx.success
	    } catch {
	      	case e: Throwable => throw e
	    } finally {
	    	if (tx != null) {
                tx.finish
            }
	    }
	    
	    result
    }
	
	def withTransaction[A](function: () => A): A =  {
        withTransactionInDatabase(function, "neo_4_j_directory");
    }

    def getSession(): GraphDatabaseService = {
        graph
    }

    def createDatabase(database: String): GraphDatabaseService = {
        var grp: GraphDatabaseService = new GraphDatabaseFactory().newEmbeddedDatabase(database)
        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            @Override
            def run() {
                grp.shutdown();
            }
        }));

        grp;
    }
}